package com.daxia.bumall.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daxia.bumall.dao.UserDesignDAO;
import com.daxia.bumall.dto.UserDesignDTO;
import com.daxia.bumall.model.UserDesign;
import com.daxia.bumall.support.Page;
import com.daxia.bumall.util.BeanMapper;

@Service
public class UserDesignService {
	
	@Autowired
	private UserDesignDAO userDesignDAO;
	
	public List<UserDesignDTO> find(UserDesignDTO query, Page page) {
		List<UserDesign> models = userDesignDAO.find(query, page);
		List<UserDesignDTO> dtos = toDTOs(models);
		return dtos;
	}
	
	public List<UserDesignDTO> findAll() {
		return this.find(new UserDesignDTO(), null);
	}
	
	public List<UserDesignDTO> find(int count) {
		Page page = new Page();
		page.setPage(1);
		page.setPageSize(count);
		return this.find(new UserDesignDTO(), page);
	}
	
	public Long create(UserDesignDTO dto) {
		UserDesign model = new UserDesign();
		toModel(model, dto);
		return userDesignDAO.create(model);
	}
	
	public UserDesignDTO load(Long id) {
	    UserDesign model = userDesignDAO.load(id);
	    return toDTO(model);
    }

	public void updateAllFields(UserDesignDTO dto) {
		UserDesign model = userDesignDAO.load(dto.getId());
		toModel(model, dto);
		userDesignDAO.update(model);
    }

	public void deleteByIds(Long[] ids) {
		if (ids != null) {
			for (Long id : ids) {
				throw new RuntimeException("未实现删除逻辑，请确认是物理删除还是逻辑删除");
				// userDesignDAO.deleteById(id);
			}
		}
    }
	
	public void deleteById(Long id) {
		this.deleteByIds(new Long[] {id});
	}

	public UserDesignDTO findOne(UserDesignDTO query) {
		UserDesign model = userDesignDAO.findOne(query);
		return toDTO(model);
	}
	
	private List<UserDesignDTO> toDTOs(List<UserDesign> models) {
		if (CollectionUtils.isEmpty(models)) {
			return new ArrayList<UserDesignDTO>(0);
		}
		List<UserDesignDTO> dtos = new ArrayList<UserDesignDTO>(models.size());
		for (UserDesign model : models) {
	        UserDesignDTO dto = toDTO(model);
	        dtos.add(dto);
        }
	    return dtos;
    }
    
    private UserDesignDTO toDTO(UserDesign model) {
		if (model == null) {
			return null;
		}
		UserDesignDTO dto = BeanMapper.map(model, UserDesignDTO.class);
		
		return dto;
	}
	
	private void toModel(UserDesign model, UserDesignDTO dto) {
		BeanMapper.copy(dto, model);
    }
	
	@SuppressWarnings("unused")
	private List<UserDesign> toModels(List<UserDesignDTO> dtos) {
		if (CollectionUtils.isEmpty(dtos)) {
			return new ArrayList<UserDesign>(0);
		}
		List<UserDesign> models = new ArrayList<UserDesign>(dtos.size());
		for (UserDesignDTO dto : dtos) {
	        UserDesign model = new UserDesign();
	        toModel(model, dto);
	        models.add(model);
        }
		return models;
	}
}
